<%@page import="java.util.InputMismatchException"%>
<%@page import="deptentity.DeptComponent"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Collection"%>
<%@page import="java.util.Scanner"%>
<%@page import="java.util.GregorianCalendar"%>
<%@page import="java.sql.Date"%>
<%@page import="empentity.EmpComponent"%>
<%@page import="java.math.BigDecimal"%>
<%@page import="empsession.EmpSessionHome"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="empsession.EmpSessionComponent"%>
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%!    private EmpSessionComponent empSession = null;
    private String ejbsessionname = "ejb/EmpSessionBean";

    public void jspInit() {
        try {
            InitialContext context = new InitialContext();
            EmpSessionHome empSessionHome = (EmpSessionHome) context.lookup(ejbsessionname);
            empSession = empSessionHome.create();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
%>
<%
    String empno = (String) request.getParameter("id");
    EmpComponent emp = empSession.getEmpByEmpno(new BigDecimal(empno));
    Collection deptList = empSession.getAllDept(), empList = empSession.getAllEmp();
    Iterator iterDept = deptList.iterator(), iterEmp = empList.iterator();
    boolean flag = true;
    if (session.getAttribute("flag") != null) {
        flag = ((Boolean) session.getAttribute("flag")).booleanValue();
    }
    extras.Log log = (extras.Log) session.getAttribute("log");
%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="styles.css"/>
        <title>Сотрудник</title>
    </head>
    <body>
        <div class="navigation">
            <%@include file="navigation.jspf"%>
        </div><br/>
        <h1>Редактирование записи</h1>
        <% if (log != null) {%>
        <div class="<%= log.isCorrect() ? "log-correct" : "log-incorrect"%>"><%= log.getMessage()%></div>
        <% } else {%><br/><% }%>
        <br/>
        <form action="editEmp.jsp">
            <table>
                <tr>
                    <th colspan="2">Сотрудник</th>
                </tr>
                <tr>
                    <th>ФИО*</th>
                    <td><input type="text" name="ename" value="<%= request.getParameter("ename") != null ? request.getParameter("ename") : emp.getEname()%>"></td>
                        <% if (request.getParameter("ename") != null && request.getParameter("ename").contentEquals("") && request.getParameter("edit") != null) {%>
                    <td class="restricting">Укажите ФИО сотрудника!</td>
                    <% flag = false;
                        }%>
                </tr>
                <tr>
                    <th>Дожность*</th>
                    <td><input type="text" name="job" value="<%= request.getParameter("job") != null ? request.getParameter("job") : emp.getJob()%>"></td>
                        <% if (request.getParameter("job") != null && request.getParameter("job").contentEquals("") && request.getParameter("edit") != null) {%>
                    <td class="restricting">Укажите должность сотрудника!</td>
                    <% flag = false;
                        }%>
                </tr>
                <tr>
                    <th>Менеджер</th>
                    <td>
                        <select name="mgr">
                            <option value=""></option>
                            <% while (iterEmp.hasNext()) {
                                    EmpComponent mgr = (EmpComponent) iterEmp.next();
                            %>
                            <option value="<%= mgr.getEmpno()%>" <%= emp.getMgr() != null && mgr.getEmpno().intValue() == emp.getMgr().intValue() ? "selected" : ""%>><%= mgr.getEname() + " (" + mgr.getJob() + ")"%></option>
                            <% }%>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th>Дата трудо-<br/>устройства*<br/>(гггг-мм-дд)</th>
                    <td><input type="text" name="hiredate" value="<%= request.getParameter("hiredate") != null ? request.getParameter("hiredate") : String.valueOf(emp.getHiredate())%>"></td>
                        <% if (request.getParameter("hiredate") != null && request.getParameter("hiredate").contentEquals("") && request.getParameter("edit") != null) {%>
                    <td class="restricting">Укажите дату трудоустройства!</td>
                    <% flag = false;
                        }%>
                </tr>
                <tr>
                    <th>Зарплата*</th>
                    <td><input type="text" name="sal" value="<%= request.getParameter("sal") != null ? request.getParameter("sal") : String.valueOf(emp.getSal())%>" maxlength="5"></td>
                        <% if (request.getParameter("sal") != null && request.getParameter("sal").contentEquals("") && request.getParameter("edit") != null) {%>
                    <td class="restricting">Укажите зарплату сотрудника!</td>
                    <% flag = false;
                        }%>
                </tr>
                <tr>
                    <th>Комиссионные</th>
                    <td><input type="text" name="comm" value="<%= emp.getComm() != null ? String.valueOf(emp.getComm()) : ""%>" maxlength="5"></td>
                </tr>
                <tr>
                    <th>Отдел*</th>
                    <td>
                        <select name="deptno">
                            <% while (iterDept.hasNext()) {
                                    DeptComponent dept = (DeptComponent) iterDept.next();
                            %>
                            <option value="<%= dept.getDeptno()%>" <%= dept.getDeptno().intValue() == emp.getDeptno().intValue() ? "selected" : ""%>><%= dept.getDname()%></option>
                            <% }%>
                        </select>
                    </td>
                    <% if (request.getParameter("deptno") != null && request.getParameter("deptno").contentEquals("") && request.getParameter("edit") != null) {%>
                    <td class="restricting">Укажите отдел!</td>
                    <% flag = false;
                        }%>
                </tr>
            </table>
            <div class="comment">поля, помеченные звёздочкой, обязательны для заполнения</div><br/>
            <input type="submit" name="edit" value="Изменить" >
            <input type="submit" name="cancel" value="Отмена">
            <input type="hidden" name="id" value="<%= emp.getEmpno()%>">
        </form>
        <%
            session.removeAttribute("log");
            session.removeAttribute("flag");
            try {
                if (request.getParameter("edit") != null && flag) {
                    Scanner scan = new Scanner(request.getParameter("hiredate")).useDelimiter("-");
                    int year = scan.nextInt();
                    int month = scan.nextInt();
                    int day = scan.nextInt();
                    scan.close();
                    BigDecimal comm = null, mgr = null;
                    if (!request.getParameter("comm").contentEquals("")) {
                        comm = new BigDecimal(request.getParameter("comm"));
                    }
                    if (!request.getParameter("mgr").contentEquals("")) {
                        mgr = new BigDecimal(request.getParameter("mgr"));
                    }
                    emp.setEname(request.getParameter("ename"));
                    emp.setJob(request.getParameter("job"));
                    emp.setMgr(mgr);
                    emp.setHiredate(new Date(new GregorianCalendar(year, month - 1, day).getTimeInMillis()));
                    emp.setSal(new BigDecimal(request.getParameter("sal")));
                    emp.setComm(comm);
                    emp.setDeptno(new BigDecimal(request.getParameter("deptno")));
                    session.setAttribute("log", new extras.Log(true, "", "Запись успешно изменена!"));
                    response.sendRedirect("viewEmp.jsp?id=" + emp.getEmpno());
                }
            } catch (NumberFormatException ex) {
                //flag = false;
                session.setAttribute("flag", Boolean.FALSE);
                session.setAttribute("log", new extras.Log(false, "", "Неверный ввод параметров! В поля зарплата и комиссионные необходимо ввести числовые значения!"));
                request.getRequestDispatcher("editEmp.jsp").forward(request, response);
            } catch (InputMismatchException ex) {
                session.setAttribute("flag", Boolean.FALSE);
                session.setAttribute("log", new extras.Log(false, "", "Неверный формат ввода даты!"));
                request.getRequestDispatcher("editEmp.jsp").forward(request, response);
            }
            if (request.getParameter("cancel") != null) {
                session.setAttribute("log", new extras.Log(false, "", "Изменение записи отклонено!"));
                response.sendRedirect("viewEmp.jsp?id=" + emp.getEmpno());
            }
        %>
    </body>
</html>
